package com.htu.courseService.Talk.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.google.common.collect.Maps;
import com.htu.courseService.Talk.dao.TalkCommentMapper;
import com.htu.courseService.Talk.entity.TalkComment;
import com.htu.courseService.Talk.service.TalkCommentService;
import com.htu.courseService.Talk.vo.TalkCommentDto;
import com.htu.courseService.common.enums.RedisCachePrefix;
import com.htu.courseService.common.util.UserUtil;
import com.htu.courseService.user.vo.UserInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class TalkCommentServiceImpl implements RedisCachePrefix, TalkCommentService {
    private final TalkCommentMapper talkCommentMapper;
    @Override
    public void addComment(TalkCommentDto talkCommentDto) {
        UserInfo userInfo = UserUtil.getUserInfo();
        TalkComment talkComment = new TalkComment();
        if(null == talkCommentDto.getParentId()){
            talkComment.setParentId(0);
        }else {
            talkComment.setParentId(talkCommentDto.getParentId());
        }
        talkComment.setTalkId(talkCommentDto.getTalkId());
        talkComment.setComment(talkCommentDto.getComment());
        talkComment.setCreatedAt(new Date());
        talkComment.setCreatedBy(userInfo.getId());
        talkCommentMapper.insert(talkComment);
    }

    @Override
    public List<Tree<Integer>> getCommentList(Integer talkId) {
        List<TalkCommentDto> nodeList = talkCommentMapper.getCommentList(talkId);
        List<TreeNode<Integer>> collect = nodeList.stream().map(talkCommentDto -> {
            TreeNode<Integer> tTreeNode = new TreeNode<>(talkCommentDto.getId(), talkCommentDto.getParentId(),
                    talkCommentDto.getComment(),
                    0);
            HashMap<String, Object> map = Maps.newHashMap();
            map.put("entity",talkCommentDto);
            tTreeNode.setExtra(map);
            return tTreeNode;
        }).toList();
        // 0表示最顶层的id是0
        List<Tree<Integer>> build = TreeUtil.build(collect, 0);
        return build;
    }
}
